import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chatbot/manager/dio_manager.dart';
import 'package:chatbot/manager/event_bus.dart';
import 'package:chatbot/manager/store_manager.dart';
import 'package:chatbot/model/completion_model.dart';
import 'package:chatbot/model/creator_list_model.dart';
import 'package:chatbot/model/event.dart';
import 'package:chatbot/page/creator_image_page.dart';
import 'package:chatbot/page/creator_text.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:cupertino_listview/cupertino_listview.dart';

import 'package:flutter/cupertino.dart';
import 'dart:convert';
import 'package:chatbot/utils/colors.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

class CreatorTabPage extends StatefulWidget {
  final SpeechToText speech;

  final SpeechToTextProvider speechProvider;

  const CreatorTabPage(
      {super.key, required this.speech, required this.speechProvider});

  @override
  _CreatorTabPageState createState() => _CreatorTabPageState();
}

class _CreatorTabPageState extends State<CreatorTabPage>
    with TickerProviderStateMixin {
  late TabController _tabController;
  List tabs = [];
  List<CreatorSection> creatorSectionList = [];
  final String allRoleTitle = "全部";
  late StreamSubscription subscription;


  @override
  void initState() {
    super.initState();

    subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile ||
          result == ConnectivityResult.wifi) {
        getAllCreatorsFromLocal();
        getCreatorFromNet();
      }
    });
  }
  getCreatorFromNet() async{
    int currentPage = 1;
    List<Creator> creatorList = [];
    bool isLastPage = false;
    int totals = 0;
    while(!isLastPage) {
      CreatorListModel creatorListModel = await DioManager.instance
          .getAllCreators(currentPage);
      if (creatorListModel.data.list.isNotEmpty) {
        currentPage += 1;
        totals = creatorListModel.data.total;
        creatorList.addAll(creatorListModel.data.list);
        isLastPage = creatorListModel.data.isLastPage;
      }
    }
    parseList(creatorList,true);

    if(totals == creatorList.length){
      debugPrint("save to local2");
      String jsonString = json.encode(creatorList);
      StoreManager.putCreatorJson(jsonString);
    }
  }

  getAllCreatorsFromLocal()  {
    String? creatorJsonString = StoreManager.getCreatorJson();
    List mapList = json.decode(creatorJsonString);

    List<Creator>creatorList = [];
    for(Map<String,dynamic> map in mapList){

      creatorList.add(Creator.fromMap(map));

    }

    parseList(creatorList,false);
  }

  void parseList(List<dynamic> list,bool isFromNet) {
    debugPrint("local111 list size=${list.length}");
    if (list.isNotEmpty) {
      Creator? previousCreator;
      int index = -1;
      creatorSectionList = [];
      tabs = [];
      tabs.add(allRoleTitle);
      for (Creator creator in list) {
        if (previousCreator == null ||
            creator.category != previousCreator.category) {
          index = index + 1;
          var sectionCreator = CreatorSection();
          sectionCreator.data = [];
          sectionCreator.title = creator.category;
          tabs.add(creator.category);
          creatorSectionList.add(sectionCreator);
          previousCreator = creator;
        }

        creatorSectionList[index].data.add(creator);
      }
      // if(tabs.isEmpty) {
        _tabController = TabController(length: tabs.length, vsync: this);
      // }
      if(isFromNet){

        _tabController.animateTo(0);

      }else{
        _tabController.animateTo(1);
      }
    }
    setState(() {});
  }

  isResponseSuccess(Map response) {
    return response.containsKey('code') && response['code'] == 200;
  }

  @override
  Widget build(BuildContext context) {
    return tabs.isEmpty
        ? Scaffold(
            backgroundColor: ChatColors.darkColor,
            body: Center(
              child: CupertinoActivityIndicator(
                  radius: 10.0, color: ChatColors.primaryColor),
            ),
          )
        : Scaffold(
            backgroundColor: ChatColors.lightColor,
            appBar: AppBar(
              elevation: 0,
              backgroundColor: ChatColors.lightColor,
              title: const Text(
                "创作",
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 16,
                    fontWeight: FontWeight.w600),
              ),
              bottom: PreferredSize(
                  preferredSize: Size.fromHeight(30.0),
                  child:TabBar(
                isScrollable: true,
                unselectedLabelColor: Color(0xff848691),
                labelStyle: TextStyle(
                    color: ChatColors.primaryColor,
                    fontSize: 15,
                    fontWeight: FontWeight.w600),
                unselectedLabelStyle:
                    const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
                dividerColor: ChatColors.darkColor,
                indicatorColor: ChatColors.primaryColor,
                controller: _tabController,
                tabs: tabs.map((e) => Tab(text: e,height:30)).toList(),
              )),
            ),
            body: TabBarView(
              //构建
              controller: _tabController,
              children: tabs.map((e) {
                if (e == allRoleTitle) {
                  return AllCreatorPage(
                      roleSectionList: creatorSectionList, title: e,speech:widget.speech,speechProvider:widget.speechProvider);
                } else {
                  return CreatorPage(
                      roleSectionList: creatorSectionList, title: e,speech:widget.speech,speechProvider:widget.speechProvider);
                }
              }).toList(),
            ),
          );
  }

  @override
  void dispose() {
    // 释放资源
    _tabController.dispose();
    super.dispose();
  }
}

class CreatorPage extends StatefulWidget {
  final List<CreatorSection> roleSectionList;
  final String title;
  final SpeechToText speech;

  final SpeechToTextProvider speechProvider;
  const CreatorPage(
      {super.key, required this.roleSectionList, required this.title,required this.speech,required this.speechProvider});

  @override
  State<StatefulWidget> createState() {
    return CreatorState(roleSectionList: roleSectionList, title: title);
  }
}

class CreatorState extends State<CreatorPage> {
  final List<CreatorSection> roleSectionList;
  final String title;
  List<Creator> roleList = [];

  CreatorState({required this.roleSectionList, required this.title});

  @override
  void initState() {
    super.initState();
    setState(() {
      for (CreatorSection section in roleSectionList) {
        if (section.title == title) {
          roleList.addAll(section.data);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ChatColors.darkColor,
      body: ListView.builder(
          itemCount: roleList.length ~/ 2 + roleList.length % 2,
          itemBuilder: (BuildContext context, int index) {
            return Row(
              children: [
                CreatorItem(roleList[index * 2],widget.speech,widget.speechProvider),
                roleList.length > (index * 2 + 1)
                    ? CreatorItem(roleList[index * 2 + 1],widget.speech,widget.speechProvider)
                    : Container()
              ],
            );
          }),
    );
  }
}

class AllCreatorPage extends StatefulWidget {
  final List<CreatorSection> roleSectionList;
  final String title;
  final SpeechToText speech;

  final SpeechToTextProvider speechProvider;
  const AllCreatorPage(
      {super.key, required this.roleSectionList, required this.title,required this.speech,required this.speechProvider});

  @override
  State<StatefulWidget> createState() {
    return AllCreatorState(roleSectionList: roleSectionList, title: title);
  }
}

class AllCreatorState extends State<AllCreatorPage> {
  final List<CreatorSection> roleSectionList;
  final String title;

  AllCreatorState({required this.roleSectionList, required this.title});

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ChatColors.darkColor,
      body: CupertinoListView.builder(
        sectionCount: roleSectionList.length,
        itemInSectionCount: (section) =>
            (roleSectionList[section].data.length ~/ 2 +
                roleSectionList[section].data.length % 2),
        sectionBuilder: (context, sectionPath, _) => Container(
          color: ChatColors.darkColor,
          width: MediaQuery.of(context).size.width,
          padding: const EdgeInsets.only(left: 12, top: 12, bottom: 6),
          child: Text(
            roleSectionList[sectionPath.section].title,
            style: const TextStyle(
                color: Colors.black, fontSize: 17, fontWeight: FontWeight.w800),
          ),
        ),
        childBuilder: (context, indexPath) {
          debugPrint(
              "indexPath.child=${roleSectionList[indexPath.section].title}");
          List roleList = roleSectionList[indexPath.section].data;
          return Row(
            children: [
              CreatorItem(roleList[indexPath.child * 2],widget.speech,widget.speechProvider),
              roleList.length > (indexPath.child * 2 + 1)
                  ? CreatorItem(roleList[indexPath.child * 2 + 1],widget.speech,widget.speechProvider)
                  : Container()
            ],
          );
        },
        separatorBuilder: (context, indexPath) => Container(
          height: 3,
        ),
      ),
    );
  }
}

class CreatorItem extends StatelessWidget {
  final Creator role;
  final SpeechToText speech;

  final SpeechToTextProvider speechProvider;
  const CreatorItem(this.role,this.speech,this.speechProvider);

  @override
  Widget build(BuildContext context) {
    return getItem(role, context);
  }

  Widget getItem(Creator role, BuildContext context) {
    return InkWell(
      highlightColor: Colors.transparent, // 透明色
      splashColor: Colors.transparent, // 透
      onTap: () {
        Navigator.push(context,
            CupertinoPageRoute(builder: (BuildContext context) {
          return role.type == 1
              ? CreatorImagePage(creator: role,speech:speech,speechProvider: speechProvider)
              : CreatorTextPage(creator: role,speech:speech,speechProvider: speechProvider,);
        }));
      },
      child: Container(
          margin: const EdgeInsets.fromLTRB(12, 12, 0, 0),
          height: 92,
          width: (MediaQuery.of(context).size.width - 36) / 2,
          decoration: BoxDecoration(
            color: ChatColors.lightColor,
            borderRadius: const BorderRadius.all(Radius.circular(12.0)),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.only(left: 8, top: 12, right: 12),
                child:

                ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child:  CachedNetworkImage(
                      imageUrl: role.cover,
                      width: 32,
                      height: 32,
                      // placeholder: (context, url) =>
                      //     const CircularProgressIndicator(color: Colors.grey),
                      errorWidget: (context, url, error) {
                        // debugPrint(error);
                        return const Icon(Icons.error);
                      },
                    )),
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text(
                          role.title,
                          style: const TextStyle(
                              color: Colors.black,
                              fontSize: 16,
                              fontWeight: FontWeight.w600),
                        ),
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 6.0, right: 6),
                      child: Text(
                        role.subTitle,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 2,
                        style: TextStyle(
                            color: Colors.black.withOpacity(0.8),
                            fontSize: 13,
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          )),
    );
  }
}
